package com.efounder.agency.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.activity.AbActivity;
import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.ospmobilelib.R;
import com.efounder.util.GlobalMap;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.view.titlebar.AbTitleBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

public class ApprovalOpinion extends AbActivity {
    private static final String TAG = "ApprovalOpinion";
    private EditText optionedittext;
    private TextView optionedcontrol;
    private ListView approvalListview;

    String commonphraseID;// 请求的详情页数据的id

    String userTag;

    List<String> listviewData = new ArrayList<String>();

    int positionDel;

    AbTitleBar mTitleBar;
    ArrayAdapter adapter;
    RelativeLayout include;
    String type;
    String systemType;
    private AsyncTask<Void, Void, JResponseObject> deleteTask;// 删除
    private AsyncTask<Void, Void, JResponseObject> dataTask;// 初始化数据
    private AsyncTask<Void, Void, JResponseObject> addDaTask;// 新增审批意见

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseApp.actManager.putActivity(TAG, this);

        setAbContentView(R.layout.approvalopinion);

        initView();

        // Bundle bundle = getIntent().getBundleExtra("dataSource");
        commonphraseID = getIntent().getStringExtra("commonphraseID");
        type = getIntent().getStringExtra("type");
        systemType = getIntent().getStringExtra("systemType");
        // commonphraseID ="";
        // systemType = "CONTRACT";
        initData();

    }

    private void initView() {

        mTitleBar = this.getTitleBar();
        mTitleBar.setVisibility(View.GONE);
        include = (RelativeLayout) findViewById(R.id.include);
        TextView title = (TextView) findViewById(R.id.fragmenttitle);
        title.setText("常用审批接口");
        LinearLayout leftbacklayout = (LinearLayout) findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);

        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                BaseApp.actManager.removeActivity(TAG);
            }
        });

        optionedittext = (EditText) findViewById(R.id.optionedittext);
        optionedcontrol = (TextView) findViewById(R.id.optionedcontrol);
        approvalListview = (ListView) findViewById(R.id.approvalListview);
        optionedcontrol.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                addData(optionedittext.getText().toString());

            }
        });
        approvalListview
                .setOnItemLongClickListener(new OnItemLongClickListener() {

                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent,
                                                   View view, int position, long id) {

                        final String aidiom = ((TextView) view).getText()
                                .toString();
                        positionDel = position;
                        new AlertDialog.Builder(ApprovalOpinion.this)
                                .setTitle("系统提示")
                                // 设置对话框标题

                                .setMessage("删除该条常用审批意见")
                                // 设置显示的内容

                                .setPositiveButton("确定",
                                        new DialogInterface.OnClickListener() {// 添加确定按钮

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {// 确定按钮的响应事件

                                                // TODO Auto-generated method
                                                // stub
                                                deleteOption();
                                                // finish();

                                            }

                                        })
                                .setNegativeButton("返回",
                                        new DialogInterface.OnClickListener() {// 添加返回按钮

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {// 响应事件

                                                // TODO Auto-generated method
                                                // stub

                                            }

                                        }).show();// 在按键响应事件中显示此对话框

                        // delApprovalOption(aidiom, commonphraseID);

                        return true;
                    }
                });
        approvalListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent();
                // 把返回数据存入Intent
                intent.putExtra("result", ((TextView) view).getText()
                        .toString());
                // 设置返回数据
                ApprovalOpinion.this.setResult(RESULT_OK, intent);
                // 关闭Activity
                ApprovalOpinion.this.finish();

            }
        });

    }

    private void deleteOption() {
        if (deleteTask != null) {
            deleteTask.cancel(true);
        }

        deleteTask = new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // 加载dialog显示
                LoadingDataUtilBlack.show(ApprovalOpinion.this);
            }

            @Override
            protected JResponseObject doInBackground(Void... params) {

                JResponseObject RO = null;
                // 判断是OA的还是合同的详情信息，以此来向服务器请求数据
                String aidiom = listviewData.get(positionDel);
                try {
                    RO = delApprovalOption(aidiom, commonphraseID);
                } catch (Exception e) {
                    // TODO: handle exception
                }

                return RO;
            }

            @Override
            protected void onPostExecute(JResponseObject result) {

                super.onPostExecute(result);

                if (result != null) {
                    // sss

                    Map<String, Object> map = result.getResponseMap();
                    EFDataSet oAdataSet = (EFDataSet) map.get(systemType);
                    if (oAdataSet != null) {
                        List<EFRowSet> efRowSets = oAdataSet.getRowSetArray();
                        if (efRowSets != null && efRowSets.size() != 0) {
                            for (int i = 0; i < efRowSets.size(); i++) {
                                EFRowSet efRowSet = efRowSets.get(i);
                                String elementname = efRowSet.getString(
                                        "elementname", "");
                                if (elementname.equals("result")) {
                                    String elementtext = efRowSet.getString(
                                            "elementtext", "");
                                    if (elementtext.equals("1")) {
                                        Toast.makeText(getApplicationContext(),
                                                "删除成功", Toast.LENGTH_SHORT)
                                                .show();
                                        listviewData.remove(positionDel);
                                        /*
                                         * adapter = new
										 * ArrayAdapter<String>(ApprovalOpinion
										 * .this,R.layout.option_items,
										 * listviewData);
										 * approvalListview.setAdapter(adapter);
										 */
                                        if (adapter != null) {
                                            adapter.notifyDataSetChanged();
                                        }
                                        break;
                                    } else {
                                        Toast.makeText(getApplicationContext(),
                                                "删除失败", Toast.LENGTH_SHORT)
                                                .show();

                                    }
                                } else {
                                    Toast.makeText(getApplicationContext(),
                                            "删除失败", Toast.LENGTH_SHORT).show();
                                    continue;
                                }

                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "删除失败",
                                Toast.LENGTH_SHORT).show();

                    }

                }
                LoadingDataUtilBlack.dismiss();

            }

            @Override
            protected void onCancelled() {

                super.onCancelled();
                LoadingDataUtilBlack.dismiss();
            }

        };
        deleteTask.executeOnExecutor(Executors.newCachedThreadPool());

    }

    private void initData() {
        if (dataTask != null) {
            dataTask.cancel(true);
        }
        dataTask = new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // 加载dialog显示
                LoadingDataUtilBlack.show(ApprovalOpinion.this);
            }

            @Override
            protected JResponseObject doInBackground(Void... params) {

                JResponseObject RO = null;
                // 判断是OA的还是合同的详情信息，以此来向服务器请求数据
                RO = getApprovalOption(commonphraseID);
                return RO;
            }

            @Override
            protected void onPostExecute(JResponseObject result) {

                super.onPostExecute(result);

                if (result != null) {

                    Map<String, Object> map = result.getResponseMap();
                    EFDataSet oAdataSet = (EFDataSet) map.get(systemType);
                    if (oAdataSet != null) {
                        List<EFRowSet> efRowSets = oAdataSet.getRowSetArray();
                        if (efRowSets != null && efRowSets.size() != 0) {
                            EFRowSet efRowSet = efRowSets.get(0);
                            EFDataSet childEfDataSet = efRowSet
                                    .getChildDataSet();
                            if (childEfDataSet != null) {
                                List<EFRowSet> childEfRowSets = childEfDataSet
                                        .getRowSetArray();
                                if (childEfRowSets != null
                                        && childEfRowSets.size() != 0) {
                                    // listviewData = new
                                    // String[childEfRowSets.size()];
                                    for (int i = 0; i < childEfRowSets.size(); i++) {

                                        EFRowSet childEfRowSet = childEfRowSets
                                                .get(i);
                                        // listviewData[i] =
                                        // childEfRowSet.getString("elementtext",
                                        // "");
                                        listviewData.add(childEfRowSet
                                                .getString("elementtext", ""));
                                    }
                                }

                                adapter = new ArrayAdapter<String>(
                                        ApprovalOpinion.this,
                                        R.layout.option_items, listviewData);
                                approvalListview.setAdapter(adapter);

                                // approvalListview.setAdapter(new
                                // ArrayAdapter<String>(ApprovalOpinion.this,android.R.layout.simple_list_item_1,
                                // listviewData));
                            }
                        }
                    }
                }
                LoadingDataUtilBlack.dismiss();

            }

            @Override
            protected void onCancelled() {

                super.onCancelled();
                LoadingDataUtilBlack.dismiss();
            }

        };

        dataTask.executeOnExecutor(Executors.newCachedThreadPool());

    }

	/*
     * 添加常用意见
	 */

    private void addData(final String aidiom) {
        if (addDaTask != null) {
            addDaTask.cancel(true);
        }
        addDaTask = new AsyncTask<Void, Void, JResponseObject>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // 加载dialog显示
                LoadingDataUtilBlack.show(ApprovalOpinion.this);
            }

            @Override
            protected JResponseObject doInBackground(Void... params) {

                JResponseObject RO = null;
                // 判断是OA的还是合同的详情信息，以此来向服务器请求数据
                RO = addApprovalOption(aidiom, commonphraseID);
                return RO;
            }

            @Override
            protected void onPostExecute(JResponseObject result) {

                super.onPostExecute(result);

                if (result != null) {

                    Map<String, Object> map = result.getResponseMap();
                    EFDataSet oAdataSet = (EFDataSet) map.get(systemType);
                    if (oAdataSet != null) {
                        List<EFRowSet> efRowSets = oAdataSet.getRowSetArray();
                        if (efRowSets != null && efRowSets.size() != 0) {
                            for (int i = 0; i < efRowSets.size(); i++) {
                                EFRowSet efRowSet = efRowSets.get(i);
                                String elementname = efRowSet.getString(
                                        "elementname", "");
                                if (elementname.equals("result")) {
                                    String elementtext = efRowSet.getString(
                                            "elementtext", "");
                                    if (elementtext.equals("1")) {
                                        Toast.makeText(getApplicationContext(),
                                                "添加成功", Toast.LENGTH_SHORT)
                                                .show();
                                        optionedittext.setText("");
                                        listviewData.add(aidiom);
                                        adapter.notifyDataSetChanged();
                                        // approvalListview.setAdapter(new
                                        // ArrayAdapter<String>(ApprovalOpinion.this,android.R.layout.simple_list_item_1,
                                        // listviewData));
                                        break;
                                    } else {
                                        Toast.makeText(getApplicationContext(),
                                                "添加失败", Toast.LENGTH_SHORT)
                                                .show();
                                        continue;
                                    }
                                }
                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "添加失败",
                                Toast.LENGTH_SHORT).show();

                    }

                    // ssss
                }
                LoadingDataUtilBlack.dismiss();

            }

            @Override
            protected void onCancelled() {

                super.onCancelled();
                LoadingDataUtilBlack.dismiss();
            }

        };
        addDaTask.executeOnExecutor(Executors.newCachedThreadPool());

    }

    /**
     * 获取常用意见接口
     *
     * @return
     */
    private JResponseObject getApprovalOption(String commonphraseID) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", systemType);
        if ("CONTRACT".equals(systemType)) {
            PO.SetValueByParamName(systemType + "_params_value",
                    commonphraseID);
        } else {
            PO.SetValueByParamName(systemType + "_params_value", commonphraseID);
        }

        PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                tokenConId);
        PO.SetValueByParamName(systemType + "_systemmethod",
                "GetIdiomListHandler");

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    /**
     * 增加审批意见
     *
     * @return
     */
    private JResponseObject addApprovalOption(String aidiom, String userTag) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", systemType);
        PO.SetValueByParamName(systemType + "_params_aidiom", aidiom);
        PO.SetValueByParamName(systemType + "_params_value", userTag);
        // PO.SetValueByParamName(systemType + "_params_value", userTag);
        PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                tokenConId);
        PO.SetValueByParamName(systemType + "_systemmethod", "AddIdiomHandler");

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    /**
     * 删除常用意见接口
     *
     * @return
     */
    private JResponseObject delApprovalOption(String aidiom, String userTag) {
        // 创建PO
        JParamObject PO = JParamObject.Create();
        JResponseObject RO = null;
        String tokenConId = GlobalMap.getProperty(systemType + "Id",
                "");

        PO.SetValueByParamName("WB_SYS_KEY", systemType);
        PO.SetValueByParamName(systemType + "_params_aidiom", aidiom);

        PO.SetValueByParamName(systemType + "_params_value", userTag);

        // PO.SetValueByParamName(systemType + "_params_value", userTag);
        PO.SetValueByParamName(systemType + "_params_tokenIDFromMoblie",
                tokenConId);

        PO.SetValueByParamName(systemType + "_systemmethod",
                "DeleteIdiomHandler");

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RO;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cannelTask(dataTask);
        cannelTask(deleteTask);
        cannelTask(addDaTask);

    }

    private void cannelTask(AsyncTask task) {
        if (task != null) {
            task.cancel(true);
        }
    }
}
